package com.daniel.cms.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.daniel.cms.entity.ArticleEntity;
import com.daniel.cms.mapper.ArticleMapper;
import com.daniel.cms.utils.Mes;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Map;

/**
 * 详细说明
 *
 * @author Daniel
 * @version V1.0
 * @date 2020/4/21 10:50
 */
@Service
public class ArticleService {
	@Autowired
	ArticleMapper mapper;

	/**
	 * 根据id获取文章信息
	 *
	 * @param id id
	 * @return Mes
	 */
	public Mes info(String id) {
		try {
			if (StringUtils.isEmpty(id + "")) {
				return Mes.error("请求主键为空");
			}
			ArticleEntity entity = mapper.selectById(id);
			return entity != null ? Mes.success(entity) : Mes.error("数据不存在");
		} catch (Exception ex) {
			return Mes.error(ex.getMessage());
		}
	}

	/**
	 * 创建文章
	 *
	 * @param entity 请求实体
	 * @return Mes
	 */
	public Mes create(ArticleEntity entity) {
		try {
			int result = mapper.insert(entity);
			return result > 0 ? Mes.success("新增成功") : Mes.error("新增失败");
		} catch (Exception ex) {
			return Mes.error(ex.getMessage());
		}
	}

	/**
	 * 更新文章
	 *
	 * @param entity 请求实体
	 * @return Mes
	 */
	public Mes update(ArticleEntity entity) {
		try {
			ArticleEntity model = mapper.selectById(entity.getId());
			if (model == null) {
				return Mes.error("数据不存在");
			}
			int result = mapper.updateById(entity);
			return result > 0 ? Mes.success("更新成功") : Mes.error("更新失败");
		} catch (Exception ex) {
			return Mes.error(ex.getMessage());
		}
	}

	/**
	 * 删除文章
	 *
	 * @param map Map
	 * @return Mes
	 */
	public Mes delete(Map<String, String> map) {
		try {
			String ids = map.get("ids");
			String[] stars = ids.split(",");
			int result = mapper.deleteBatchIds(Arrays.asList(stars));
			return result > 0 ? Mes.success("删除成功") : Mes.error("删除失败");
		} catch (Exception ex) {
			return Mes.error(ex.getMessage());
		}
	}

	/**
	 * 获取数据
	 *
	 * @param current 页索引
	 * @param limit   页大小
	 * @param name    用户名
	 * @return Mes
	 */
	public Mes list(int current, int limit, String name) {
		try {
			Page<ArticleEntity> page = new Page<>(current, limit);
			QueryWrapper<ArticleEntity> queryWrapper = new QueryWrapper<>();
			if (!StringUtils.isEmpty(name)) {
				queryWrapper.like("title", name);
			}
			queryWrapper.orderByAsc("id");
			mapper.selectPage(page, queryWrapper);
			return Mes.success(page);
		} catch (Exception ex) {
			return Mes.error(ex.getMessage());
		}
	}
}
